<?php

namespace lxs\tiktok;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class BaseController
{

    private mixed $secret;
    private mixed $appId;

    public function __construct()
    {
        $this->appId = env('TIKTOK_APP_ID');
        $this->secret = env('TIKTOK_APP_SECRET');
    }

    /**
     * 获取accessToken
     */
    protected function getAccessToken($appid, $secret): ?string
    {
        if ($appid != '' && $secret != '') {
            $this->appId = $appid;
            $this->secret = $secret;
        }
        $url = "https://open.douyin.com/oauth/client_token";
        $params = [
            'grant_type' => 'client_credential',
            'appid' => $appid,
            'secret' => $secret
        ];
        $response = Http::post($url, $params);
        if ($response->successful()) {
            $data = $response->json();
            if ($data['message'] == 'success') {
                if ( $appid == '' && $secret == '') {
                    Cache::put('tiktok:access_token', $data['data']['access_token'], $data['data']['expires_in'] - 60);
                }
                return $data['data']['access_token'];
            } else {
                Log::error(date('Y-m-d H:i:s') . '获取access_token失败' . PHP_EOL . $response->body());
                return null;
            }
        }
        return null;
    }

}
